package com.youkeda.yikao.web.control;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * @author ：chenzikang
 * @date ： 2019/9/4 11:29
 */

@Controller
public class CaptchaControl {

    @Autowired
    private DefaultKaptcha kaptcha;


    @RequestMapping(path = "/captcha")
    private void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control", "post-check=0,pre-check=0");
        response.setHeader("pragma", "no-cache");

        // 返回一个图片
        response.setContentType("image/png");

        //创建文本保存验证码
        String capText = kaptcha.createText();
        //将验证码保存到session中
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        //通过文本创建图片
        BufferedImage bi = kaptcha.createImage(capText);

        //创建输出流
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "png", out);

        try {
            out.flush();
        } finally {
            out.close();
        }

    }


    @Bean
    public DefaultKaptcha initKaptcha() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();

        properties.put(Constants.KAPTCHA_IMAGE_HEIGHT,"40");
        properties.put(Constants.KAPTCHA_IMAGE_WIDTH,"145");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE,"32");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING,"123456789");
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;

    }
}
